#include "UdpServer.hpp"
#include <memory>
#include <cstdio>
#include <vector>

void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " port[1024+]\n"
         << endl;
}

string Handler(const string &info,const string& clientip,uint16_t clientport)
{
    cout<<"["<<clientip<<" : "<<clientport<<"]# "<<info<<endl;
    string ret = "Server get a message: ";
    ret += info;
    cout << info << endl;
    return ret;
}

bool SafeCheck(string cmd)
{
    cout<<"get a request cmd: "<<cmd<<endl;
    std::vector<std::string> key_word = {
        "rm","mv","cp","kill","unlink","uninstall","yum","top","while"
    };
    for(auto word:key_word)
    {
        auto pos = cmd.find(word);
        if(pos!=string::npos) return false;
    }
    return true;
}

string ExcuteCommand(const string &cmd)
{
    if(!SafeCheck(cmd)) return "Bad man";
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    string result;
    char buffer[4096];
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr)
            break;
        result += ok;
    }

    pclose(fp);

    return result;
}

//.udpserver port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);

    std::unique_ptr<UdpServer> svr(new UdpServer(port));

    svr->Init();
    // svr->Run(ExcuteCommand);
    svr->Run();

    return 0;
}